﻿using Autodesk.AutoCAD.DatabaseServices;

namespace AutoCADDotNetLibrary
{
    /// <summary>
    /// 空间
    /// </summary>
    public enum Space
    {
        /// <summary>
        /// 当前空间
        /// </summary>
        CurrentSpace = 0,

        /// <summary>
        /// 模型空间
        /// </summary>
        ModelSpace = 1,

        /// <summary>
        /// 纸质空间
        /// </summary>
        PaperSpace = 2,
    }

    /// <summary>
    /// 实体扩展
    /// </summary>
    public static class EntityExtention
    {
        /// <summary>
        /// 实体添加到空间
        /// </summary>
        /// <param name="db">dwg数据库</param>
        /// <param name="spaceMode">打开空间</param>
        /// <param name="isDispose">是否关闭实体</param>
        /// <param name="ents">实体集</param>
        public static void AddEntityToSpace(this Database db, Space spaceMode, bool isDispose, params Entity[] ents)
        {
            Transaction trans = db.TransactionManager.TopTransaction;
            BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);

            BlockTableRecord space;
            switch (spaceMode)
            {
                case Space.CurrentSpace:
                    space = (BlockTableRecord)trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                    break;
                case Space.ModelSpace:
                    space = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                    break;
                case Space.PaperSpace:
                    space = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.PaperSpace], OpenMode.ForWrite);
                    break;
                default:
                    space = (BlockTableRecord)trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                    break;
            }

            foreach (Entity ent in ents)
            {
                space.AppendEntity(ent);
                trans.AddNewlyCreatedDBObject(ent, true);
            }

            if (isDispose)
            {
                foreach (Entity ent in ents)
                {
                    ent.Dispose();
                }
            }
        }

        /// <summary>
        /// 实体添加到当前空间，并Dispose()，之后是ents不能使用的
        /// </summary>
        /// <param name="db">dwg数据库</param>
        /// <param name="ents">实体集</param>
        public static void AddEntityToSpace(this Database db, params Entity[] ents)
        {
            db.AddEntityToSpace(Space.CurrentSpace, true, ents);
        }
    }
}
